package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandle {
    @ExceptionHandler(SQLException.class)
    public R<String> exceptionHandler(SQLException exception){
        log.error(exception.getMessage());
        if(exception.getMessage().contains("Duplicate entry")){
            return R.error("数据库异常，数据已经存在");
        }else if(exception.getMessage().contains("Data truncation")){
            return R.error("数据库异常，长度太长");
        } return R.error("未知异常");
    }
    @ExceptionHandler(CustomException.class)
    public R<String> CustomException(CustomException exception){
        log.error(exception.getMessage());
        return R.error(exception.getMessage());
    }

}
